package com.xx.doublexchat.common.user.event.listener;

import com.xx.doublexchat.common.user.dao.UserDao;
import com.xx.doublexchat.common.user.domain.entity.User;
import com.xx.doublexchat.common.user.domain.enums.IdempotentEnum;
import com.xx.doublexchat.common.user.domain.enums.ItemEnum;
import com.xx.doublexchat.common.user.domain.enums.ItemTypeEnum;
import com.xx.doublexchat.common.user.event.UserRegisterEvent;
import com.xx.doublexchat.common.user.service.IUserBackpackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 用户注册事件监听者
 */
@Component
public class UserRegisterListener {
    @Autowired
    private IUserBackpackService userBackpackService;

    @Autowired
    private UserDao userDao;

    /**
     * 发送改名卡
     * 监听用户注册事件, 事务提交后执行
     *
     * @param userRegisterEvent
     */
    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendCard(UserRegisterEvent userRegisterEvent) {
        User user = userRegisterEvent.getUser();
        userBackpackService.acquireItem(user.getId(), ItemEnum.MODIFY_NAME_CARD.getId()
                , IdempotentEnum.UID, user.getId().toString());
    }

    /**
     * 发送徽章
     * @param userRegisterEvent
     */
    @Async
    @TransactionalEventListener(classes = UserRegisterEvent.class,phase = TransactionPhase.AFTER_COMMIT)
    public void sendBadge(UserRegisterEvent userRegisterEvent) {
        User user = userRegisterEvent.getUser();
        int registerCount = userDao.count();
        if (registerCount <= 10) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP10_BADGE.getId()
                    , IdempotentEnum.UID, user.getId().toString());
        } else if (registerCount <= 100) {
            userBackpackService.acquireItem(user.getId(), ItemEnum.REG_TOP100_BADGE.getId()
                    , IdempotentEnum.UID, user.getId().toString());
        }

    }
}
